import { getLocal } from '@/utils/local'
import store from '../store'
import * as types from '@/store/action-types'

class WS {
    constructor(config = {}) {
        this.url = config.url || 'localhost'
        this.port = config.port || 4000
        this.protocol = config.protocol || 'ws'
        this.time = config.time || 30 * 1000
        this.ws = null
    }
    onOpen = () => {
        this.ws.send(JSON.stringify({
            type: 'auth',
            data: getLocal('token')
        }))
    }
    onMessage = (e) => {
        let { type, data } = JSON.parse(e.data)
        console.log('onMessage', type, data);
        
        switch(type) {
            case 'noAuth':
                console.log('没有权限');
                break;
            case 'heartCheck':
                this.checkServer()
                this.ws.send(JSON.stringify({
                    type: 'heartCheck'
                }));
                break;
            default:
                store.commit(types.SET_MESSAGE, data)
        }
    }
    onError = () => {
        setTimeout(() => {
            this.create()
        }, 1000)
    }
    onClose = () => {
        this.ws.close()
    }
    create() {
        this.ws = new WebSocket(`${this.protocol}://${this.url}:${this.port}`)
        this.ws.onopen = this.onOpen
        this.ws.onmessage = this.onMessage
        this.ws.onclose = this.onClose
        this.ws.onerror = this.onError
    }
    checkServer() {
        clearTimeout(this.timer)
        this.timer = setTimeout(() => {
            this.onClose()
            this.onError()
        }, this.time + 1000)
    }
    send = (msg) => {
        this.ws.send(JSON.stringify(msg))
    }
}

export default WS;